define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            $(".btn-edit").data("area", ["1000px", "80%"]);//编辑
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/order/index' + location.search,
                    add_url: 'pt/order/add',
                    edit_url: 'pt/order/edit',
                    del_url: 'pt/order/del',
                    multi_url: 'pt/order/multi',
                    import_url: 'pt/order/import',
                    table: 'pt_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        // {field: 'id', title: __('Id')},
                        {field: 'order_source', title: __('Order_source') ,searchList:{'1':'手工录入','2':'小程序','3':'app'}, formatter:function(v,r,index){ 
                            let source_name = '';
                            switch (v) {
                                case 1:
                                    source_name = '手工录入';
                                    break;
                                case 2:
                                    source_name = '小程序';
                                    break;
                                case 3:
                                    source_name = 'app';
                                    break;
                                default:
                                    source_name = '未知';
                                    break;
                            }
                            return `<span class="label label-primary">${source_name}</span>`;
                        }},
                        {field: 'user_source', title: __('User_source') ,searchList:{'1':'本年新进','2':'上年结转','3':'他组转移'}, formatter:function(v,r,index){ 
                            let source_name = '';
                            switch (v) {
                                case 1:
                                    source_name = '本年新进';
                                    break;
                                case 2:
                                    source_name = '上年结转';
                                    break;
                                case 3:
                                    source_name = '他组转移';
                                    break;
                                default:
                                    source_name = '未知';
                                    break;
                            }
                            return `<span class="label label-primary">${source_name}</span>`;
                        }},
                        {field: 'year', title: __('Year')},
                        {field: 'order_no', title: __('Order_no'), operate: 'LIKE'},
                        {field: 'pt_grade', title: __('Pt_grade')},
                        {field: 'serial_no', title: __('Serial_no'), operate: 'LIKE'},
                        {field: 'user_name', title: __('User_name'), operate: 'LIKE'},
                        {field: 'order_level', title: __('Order_level') ,searchList:{'1':'资料','2':'包过'}, formatter:function(v,r,index){ 
                            let level_name = '';
                            switch (v) {
                                case 1:
                                    level_name = '资料';
                                    break;
                                case 2:
                                    level_name = '包过';
                                    break;
                            }
                            return `<span class="label label-primary">${level_name}</span>`;
                        }},
                        {field: 'contract_term', title: __('Contract_term'), operate:false},
                        {field: 'contract_start_time', title: __('Contract_start_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'contract_end_time', title: __('Contract_end_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'contract_fee', title: __('Contract_fee'), operate:false},
                        // {field: 'institution_id', title: __('Agency_id')},
                        {field: 'agency_name', title: __('Agency_name'), operate: 'LIKE'},
                        {field: 'series_name', title: __('Series_name'), operate: 'LIKE'},
                        {field: 'major_name', title: __('Major_name'), operate: 'LIKE'},
                        {field: 'company', title: __('Company'), operate: 'LIKE'},
                        {field: 'leader_name', title: __('Leader_name'), operate: 'LIKE'},
                        // {field: 'province_id', title: __('Province_id')},
                        // {field: 'city_id', title: __('City_id')},
                        // {field: 'district_id', title: __('District_id')},
                        {field: 'district_name', title: __('District_name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'order_status', title: __('Order_status') ,searchList:{'1':'新增','2':'主管审核','3':'准备','4':'定稿','5':'资格审查通过','9':'未通过','10':'未定稿退费','11':'已定稿退费'}, formatter:function(v,r,index){ 
                            let status_name = '';
                            switch (v) {
                                case 1:
                                    status_name = '新增';
                                    break;
                                case 2:
                                    status_name = '主管审核';
                                    break;
                                case 3:
                                    status_name = '准备';
                                    break;
                                case 4:
                                    status_name = '定稿';
                                    break;
                                case 5:
                                    status_name = '资格审查通过';
                                    break;
                                case 9:
                                    status_name = '未通过';
                                    break;
                                case 10:
                                    status_name = '未定稿退费';
                                    break;
                                case 11:
                                    status_name = '已定稿退费';
                                    break;
                            }
                            return `<span class="label label-primary">${status_name}</span>`;
                        }},
                        {field: 'social_security_trans', title: __('Social_security_trans'),operate:false,formatter:function(v,r,index){ 
                            let status_name = '';
                            switch (v) {
                                case 0:
                                    status_name = '否';
                                    break;
                                case 1:
                                    status_name = '是';
                                    break;
                            }
                            return `<span class="label label-primary">${status_name}</span>`;
                        }},
                        {field: 'assign_company', title: __('Assign_company'), operate:false},
                        {field: 'review_form_status', title: __('Review_form_status'),operate:false ,searchList:{'0':'未取回','1':'取回','2':'已寄送'}, formatter:function(v,r,index){ 
                            let status_name = '';
                            switch (v) {
                                case 0:
                                    status_name = '未取回';
                                    break;
                                case 1:
                                    status_name = '取回';
                                    break;
                                case 2:
                                    status_name = '已寄送';
                                    break;
                            }
                            return `<span class="label label-primary">${status_name}</span>`;
                        }},
                        {field: 'cert_download', title: __('Cert_download'),operate:false, formatter:function(v,r,index){ 
                            let status_name = '';
                            switch (v) {
                                case 0:
                                    status_name = '否';
                                    break;
                                case 1:
                                    status_name = '是';
                                    break;
                            }
                            return `<span class="label label-primary">${status_name}</span>`;
                        }},
                        // {field: 'edu_cert_situation', title: __('Edu_cert_situation'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'edu_supplement', title: __('Edu_supplement'),operate:false,formatter:function(v,r,index){ 
                            let status_name = '';
                            switch (v) {
                                case 0:
                                    status_name = '否';
                                    break;
                                case 1:
                                    status_name = '是';
                                    break;
                            }
                            return `<span class="label label-primary">${status_name}</span>`;
                        }},
                        {field: 'ass_worker_supplement', title: __('Ass_worker_supplement'),formatter:function(v,r,index){ 
                            let status_name = '';
                            switch (v) {
                                case 0:
                                    status_name = '否';
                                    break;
                                case 1:
                                    status_name = '是';
                                    break;
                            }
                            return `<span class="label label-primary">${status_name}</span>`;
                        }},
                        {field: 'utel', title: __('Utel'), operate: 'LIKE'},
                        {field: 'id_card', title: __('Id_card'), operate: 'LIKE'},
                        {field: 'leader_commission', title: __('Leader_commission'), operate:false},
                        {field: 'leader_bonus', title: __('Leader_bonus'), operate:false},
                        {field: 'material_fee', title: __('Material_fee'), operate:false},
                        {field: 'consulting_fee', title: __('Consulting_fee'), operate:false},
                        {field: 'cont_edu_fee', title: __('Cont_edu_fee'), operate:false},
                        {field: 'special_add_fee', title: __('Special_add_fee'), operate:false},
                        {field: 'total_commis_amount', title: __('Total_commis_amount'), operate:false},
                        {field: 'payment_amount', title: __('Payment_amount'), operate:false},
                        {field: 'remittance_frequency', title: __('Remittance_frequency'), operate:false},
                        {field: 'payoff', title: __('Payoff'), operate:false},
                        {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter:Table.api.formatter.buttons,
                            buttons:[
                                {
                                    name: 'edit',
                                    text: '编辑',
                                    title: '订单编辑',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    extend:' data-area=\'["1000px", "800px"]\' data-shade=\'0.3\'',
                                    icon: 'fa fa-edit',
                                    url: 'pt/order/edit',
                                    visible: function (row) {
                                        return true;
                                    }
                                },
                                {
                                    name: 'delete',
                                    text: '删除',
                                    title: '确定要删除这个订单吗？',
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    icon: 'fa fa-trash',
                                    url: 'pt/order/del',
                                    extend: ' data-confirm="确定要删除这个订单吗？删除后无法恢复！"',
                                    visible: function (row) {
                                        if(row.order_status==1){
                                            return true;
                                        }
                                        return false;
                                    }
                                }
                                // ,{
                                //     name: 'user_offer',
                                //     text: '人员管理',
                                //     title: '人员管理',
                                //     classname: 'btn btn-xs btn-info btn-dialog',
                                //     extend:' data-area=\'["800px", "700px"]\' data-shade=\'0.3\'',
                                //     icon: 'fa fa-user',
                                //     url: function (row) {
                                //         return 'pt/order/user_offer?order_id=' + row.id;
                                //     },
                                //     visible: function (row) {
                                //         return true;
                                //     }
                                // }
                            ]}
                    ]
                ]
            });
            table.on('post-body.bs.table', function () {
                $(".btn-editone").data("area", ["1200px", "800px"]);
             
            })

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            // 监听机构选择的change事件
            $(".selectpage").on("change", function(){
                var selectedItem = $(this).selectPage('getValue');
                
               
                if (selectedItem) {
                    //如果是  [series_name ,major_name ,agency_name] 中包含的
                    if($.inArray(selectedItem[0].dataset.field, ['agency_name']) !== -1){
                        $("#c-"+selectedItem[0].dataset.field).val(selectedItem[0].value || '');
                    }else if($.inArray(selectedItem[0].dataset.field, ['grade_name']) !== -1){
                        // 获取所有得到的记录
                        let data = $(this).data("selectPageObject").data
                        // 获取返回值
                        let value = $("input[name='"+$(this).attr('name').slice(0,-5)+"']").val()
                        const item = data.find(itm => itm.id == value); // 使用 == 自动类型转换
                   
                        if (item) {
                            $("#c-pt_grade").val(item.grade_code);
                        }
                      
                    }else {
                        // 未选中时清空相关字段
                        $("#c-"+selectedItem[0].dataset.field).val('');
                    
                    }
                }

            });
            
       
            // 监听省市区选择变化，自动更新district_name字段
            $('.province, .city, .area').on('change', function() {
                Controller.updateDistrictName();
                //updateDistrictName();
            });

            $(".series ").on("change", function(){
                if($(".series").find('option:selected').text()){
                    $("#c-series_name").val($(".series").find('option:selected').text());
                }
                
            });

            $(".major").on("change", function(){
                if($(".major").find('option:selected').text()){
                    $("#c-major_name").val($(".major").find('option:selected').text());
                }
            });

            
            
        },
        edit: function () {
            Controller.api.bindevent();
            
         // 监听机构选择的change事件
         $(".selectpage").on("change", function(){
            var selectedItem = $(this).selectPage('getValue');
            
           
            if (selectedItem) {
                //如果是  [series_name ,major_name ,agency_name] 中包含的
                if($.inArray(selectedItem[0].dataset.field, ['agency_name']) !== -1){
                    $("#c-"+selectedItem[0].dataset.field).val(selectedItem[0].value || '');
                }else if($.inArray(selectedItem[0].dataset.field, ['grade_name']) !== -1){
                    // 获取所有得到的记录
                    let data = $(this).data("selectPageObject").data
                    // 获取返回值
                    let value = $("input[name='"+$(this).attr('name').slice(0,-5)+"']").val()
                    const item = data.find(itm => itm.id == value); // 使用 == 自动类型转换
                     console.log('item', item);
                    if (item) {
                        $("#c-pt_grade").val(item.grade_code);
                    }
                  
                }else {
                    // 未选中时清空相关字段
                    $("#c-"+selectedItem[0].dataset.field).val('');
                
                }
            }

        });
        
   
        // 监听省市区选择变化，自动更新district_name字段
        $('.province, .city, .area').on('change', function() {
            Controller.updateDistrictName();
            //updateDistrictName();
        });

        $(".series ").on("change", function(){
            if($(".series").find('option:selected').text()){
                $("#c-series_name").val($(".series").find('option:selected').text());
            }
            
        });

        $(".major").on("change", function(){
            if($(".major").find('option:selected').text()){
                $("#c-major_name").val($(".major").find('option:selected').text());
            }
        });

            //updateDistrictName();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            
          
            
            
        },
        user_offer: function () {
            // 不绑定FastAdmin的自动处理，完全自定义
            // Controller.api.bindevent();
            
            // 绑定自定义验证和提交处理
            $('#user-offer-form').on('submit', function(e) {
                e.preventDefault(); // 先阻止默认提交
                
                // 自定义验证逻辑
                let invalidPositions = [];
                let selectElements = $('select.offer-select, select[name*="[user_id]"]');
                
                selectElements.each(function() {
                    var $select = $(this);
                    var positionName = $select.closest('tr').find('td:first strong').text().trim();
                    var value = $(this).val();
            
                    if (!value || value === '') {
                        invalidPositions.push(positionName);
                    }
                });
            
                // 如果有未选择项，提示并中断
                if (invalidPositions.length > 0) {
                    let message = '必须为所有专员类型选择人员才能提交！\n\n未选择的专员类型：\n' + invalidPositions.join('\n');
                    Toastr.error(message);
                    return false; // 阻止提交
                }
                
                // 验证通过，手动提交表单
                var formData = $(this).serialize();
                
                $.ajax({
                    url: 'pt/order/save_offers',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(data) {
                        if (data.code == 1) {
                            Toastr.success(data.msg || '操作成功');
                            setTimeout(function() {
                                parent.layer.closeAll();
                                var timestamp = new Date().getTime();
                                parent.location.href = parent.location.pathname + parent.location.search + (parent.location.search ? '&' : '?') + '_t=' + timestamp;
                            }, 1500);
                        } else {
                            Toastr.error(data.msg || '操作失败');
                        }
                    },
                    error: function(xhr, status, error) {
                        Toastr.error('网络错误，提交失败！');
                    }
                });
            });
            
           
        },

        // 更新地区名称的函数
        updateDistrictName: function () {
            var provinceSelect = $('.province');
            var citySelect = $('.city');
            var areaSelect = $('.area');
            var districtNameInput = $('#c-district_name');
            
            var provinceText = provinceSelect.find('option:selected').text();
            var cityText = citySelect.find('option:selected').text();
            var areaText = areaSelect.find('option:selected').text();
            
            // 组合完整的地区名称
            var fullDistrictName = '';
            if (provinceText && provinceText !== '请选择') {
                fullDistrictName += provinceText;
            }
            if (cityText && cityText !== '请选择') {
                fullDistrictName += cityText;
            }
            if (areaText && areaText !== '请选择') {
                fullDistrictName += areaText;
            }
            
            // 更新district_name字段
            districtNameInput.val(fullDistrictName);
        },
      
       
            
    };
    
    return Controller;
});
